package telco.provider.manager;

import java.util.Iterator;
import java.util.Vector;

import swa2012.telco.broker.beans.Client;
import swa2012.telco.broker.beans.Message;


public class MessageManager {
	private static final MessageManager instance = new MessageManager();
	private Vector<Message> messages = new Vector<Message>(); 
	
	//Constructor
    private MessageManager() 
    {
    	
    }
 
    //Gets the singleton instance of this class
    public static MessageManager getInstance() 
    {
        return instance;
    }
	
    //Returns all unsent messages
	public Vector<Message> getMessages()
	{
		return messages;
	}
	
	public Vector<Message> getMessagesForReceiver (Client c)
	{
		Vector<Message> clientMsg = new Vector<Message>();
		
		//For each unsent message check if client is receiver
		for( Iterator< Message > it = messages.iterator(); it.hasNext() ; )
        {
            Message msg = it.next();
            if(c.equals(msg.getReceiver()))
			{
				clientMsg.add(msg);
			}
        }
		
		messages.removeAll(clientMsg);
		
		return clientMsg;
	}
	
	//Adds message to send and returns true if adding worked
	public boolean addMessage(Message m)
	{
		if(!messages.contains(m))
		{
			return messages.add(m);
		}
		else return false;
	}
	
	//Removes message if it exists in the collection and, in this case, returns true
	public boolean removeMessage(Message c)
	{
		return messages.remove(c);
	}
	
	public void sendMessage(Message msg)
	{
		/*
		 * Check if receiver is Broker or Client. 
		 * If Broker: send.
		 * If Client: save to undelivered messages and wait until client gets message.
		 */
		if(ProviderManager.getInstance().getMe().equals(msg.getReceiver().getProvider()))
		{
			addMessage(msg);
		}
		
		else BrokerManager.getInstance().sendMessage(msg);
	}
	
	//Remove all undelivered messages for cleanup
	public void deleteAllMessages()
	{
		messages.clear();
	}
}
